package com.event;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.EventListener;
import java.util.EventObject;
import java.util.HashSet;
import java.util.Set;

/**
 * @author: LCG
 * @date: 2022-04-16 16:49:20
 * @description:
 **/
public class MyEventSource {

    private String userName;

    private Set<EventListener> eventListenerSet=new HashSet<>();

    /** 
     * @author: LCG
     * @date: 2022-04-16 16:51:12
     * @description:  为一个事件源注册一个事件的监听
     */
    public MyEventSource addListener(EventListener eventListener){
        eventListenerSet.add(eventListener);
        return this;
    }


    /** 
     * @author: LCG
     * @date: 2022-04-16 16:52:28
     * @description:  当有一个事件发生的时候触发通知行为（也就是执行listener中的通知方法）
     */
    public void notifyMsg() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        for (EventListener eventListener : eventListenerSet) {
            Method onEvent = eventListener.getClass().getDeclaredMethod("onEvent", EventObject.class);
            MyJavaEvent myJavaEvent=new MyJavaEvent(this.userName);
            onEvent.invoke(eventListener,myJavaEvent);
        }
    }


    public void setUserName(String userName) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        this.userName = userName;
        this.notifyMsg();
    }
}
